package com.coollang.smartbra.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.coollang.smartbra.R;
import com.coollang.smartbra.adapter.SportPlanDataAdapter;
import com.coollang.smartbra.adapter.SportPlanGridViewAdapter;
import com.coollang.smartbra.interfaces.SportPlanView;
import com.coollang.smartbra.model.SportPlanModel;
import com.coollang.smartbra.presenter2.NewSportPlanActivityPresenter;
import com.coollang.smartbra.utils.DisplayUtils;
import com.coollang.smartbra.utils.TranslucentSystemBarUtils;
import com.coollang.smartbra.utils.WindowManagerUtils;
import com.coollang.smartbra.views.GetMoveScrollView;
import com.coollang.smartbra.views.SlowHorizontalScrollView;
import com.nineoldandroids.view.ViewHelper;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author : Timmy
 * @date : 2018/1/17
 * @fuction:
 */
public class NewSportPlanActivity extends AbstractMvpActivity<SportPlanView, NewSportPlanActivityPresenter> implements SportPlanView {

    @BindView(R.id.content)
    RelativeLayout mContent;
    @BindView(R.id.tv_title)
    TextView mTvTitle;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.view_top)
    View viewTop;
    @BindView(R.id.scroll_plan)
    GetMoveScrollView mScrollPlan;
    @BindView(R.id.topbar_bg)
    View topbarBg;
    @BindView(R.id.iv_back)
    ImageView mIvBack;
    @BindView(R.id.grid)
    GridView mGridView;
    @BindView(R.id.backto_today)
    ImageView mBacktoToday;
    @BindView(R.id.status_bar)
    View mStatusBar;
    @BindView(R.id.horizontalscrollview)
    SlowHorizontalScrollView horizontalscrollview;
    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;

    // ======================================

    private SportPlanGridViewAdapter mAdapter;
    private int maxScroll;
    private int mScreenWidth;

    private Handler mHandler = new Handler();
    private SportPlanDataAdapter mSportPlanDataAdapter;
    private ProgressDialog mProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sport_plan);
        ButterKnife.bind(this);
        TranslucentSystemBarUtils.showChenJinZhuangTaiLan(mStatusBar, this, mContent);

        initView();

        initData();
    }

    private void initData() {
        showProgressDialog("", "正在加载数据...");
        getPresenter().initData();
    }

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    protected NewSportPlanActivityPresenter createPresenter() {
        return new NewSportPlanActivityPresenter();
    }

    private void initView() {
        initScroll();
        getWindowWith();

        mAdapter = new SportPlanGridViewAdapter(this);
        mGridView.setAdapter(mAdapter);

        mRecyclerView.setNestedScrollingEnabled(false);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mSportPlanDataAdapter = new SportPlanDataAdapter(null);
        mRecyclerView.setAdapter(mSportPlanDataAdapter);
    }

    private void initScroll() {
        viewTop.setAlpha(0);
        maxScroll = DisplayUtils.dip2px(this, 130);
        mScrollPlan.setScrollViewListener(new GetMoveScrollView.ScrollChangeListener() {
            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {
                if (t <= 0) {
                    topbarBg.setAlpha(1);
                    mTvTitle.setAlpha(1);
                    setTitleTextColor(R.color.black_666);
                } else if (t >= maxScroll) {
                    //超过时,只能滑动到这个最大距离
                    mScrollPlan.smoothScrollTo(0, maxScroll);
                    topbarBg.setAlpha(0);
                    mTvTitle.setAlpha(1);
                    setTitleTextColor(R.color.white);
                } else {
                    if (t > maxScroll / 2) {
                        setTitleTextColor(R.color.white);
                        ViewHelper.setAlpha(mTvTitle, (float) ((t - maxScroll / 2) / (float) (maxScroll / 2) + 0.1));
                    } else {
                        setTitleTextColor(R.color.black_666);
                        ViewHelper.setAlpha(mTvTitle, (float) (1 - t / (float) (maxScroll / 2) + 0.1));
                    }
                    if ((1 - t / (float) maxScroll) <= 0) {
                        ViewHelper.setAlpha(topbarBg, (float) 0);
                    } else {
                        ViewHelper.setAlpha(topbarBg, (1 - t / (float) maxScroll));
                    }
                }
            }
        });
    }


    @OnClick({R.id.backto_today, R.id.iv_back})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backto_today:

                int count = mAdapter.getCount();
                if (count == 0) {
                    Toast.makeText(this, "计划不存在", Toast.LENGTH_SHORT).show();
                }else  {
                    int todayPosition = getPresenter().getTodayPosition();
                    setSelectPosition(todayPosition);
                    // 隐藏今日布局
                    setBackToToDayVisibility(todayPosition);
                    scrollTodayPosition(todayPosition);
                    setDayData(todayPosition);
                }
                break;
            case R.id.iv_back:
                finish();
                break;
            default:
                break;
        }
    }

    public void setTitleTextColor(int titleTextColor) {
        mTvTitle.setTextColor(ContextCompat.getColor(this, titleTextColor));
    }

    /**
     * 获取屏幕宽度
     */
    private void getWindowWith() {
        // 取得窗口属性
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        // 窗口的宽度
        mScreenWidth = dm.widthPixels;
    }


    @Override
    public void setPlanData(List<SportPlanModel.DataBean> data) {

        if (data != null) {
            setGridView(data.size());
            final int todayPosition = getPresenter().getTodayPosition();
            mAdapter.setToDayPosition(todayPosition);
            mAdapter.addData(data);
            setClickPosition(todayPosition);

            String date = (todayPosition + 1) + "/28天";
            mTvDate.setText(date);

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    scrollTodayPosition(todayPosition);
                    setDayData(todayPosition);
                    hideProgressDialog();
                }
            }, 1000);
        } else {
            hideProgressDialog();
        }
    }

    public void setGridView(int size) {
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WindowManagerUtils.getWindowWidth(this) * 4, LinearLayout.LayoutParams.FILL_PARENT);

        // 设置GirdView布局参数,横向布局的关键
        mGridView.setLayoutParams(params);

        // // 设置列表项宽
        mGridView.setColumnWidth(WindowManagerUtils.getWindowWidth(this) / 7);

        // / 设置列表项水平间距
        mGridView.setHorizontalSpacing(0);
        mGridView.setStretchMode(GridView.NO_STRETCH);

        // 设置列数量=列表集合数
        mGridView.setNumColumns(size);

        //设置初始选中是计时
        //setClickPosition(mPresenter.currentPosition);
        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (mAdapter.getCurrentPosition() != position) {
                    setBackToToDayVisibility(position);
                    setSelectPosition(position);
                    setDayData(position);
                    scrollTodayPosition(position);
                }
            }
        });
    }

    /**
     * 点击选中了一个
     */
    private void setClickPosition(int position) {
        mGridView.setSelection(position);
        setSelectPosition(position);
        setBackToToDayVisibility(position);
    }

    /**
     * 回到今天的布局显示
     */
    private void setBackToToDayVisibility(int position) {
        if (position != getPresenter().getTodayPosition()) {
            mBacktoToday.setVisibility(View.VISIBLE);
        } else {
            mBacktoToday.setVisibility(View.GONE);
        }
    }

    private void setSelectPosition(int position) {
        mAdapter.notif(position);
    }

    private void scrollTodayPosition(int todayPosition) {
        View childAt = mGridView.getChildAt(todayPosition);
        if (null != childAt) {
            int x = (int) childAt.getX() - (mScreenWidth / 2);
            int y = this.maxScroll;
            horizontalscrollview.smoothScrollToSlow(x, y, 1000);
        }
    }

    /**
     * 更新对应天的数据
     */
    private void setDayData(int position) {
        List<SportPlanModel.DataBean> sportPlanData = getPresenter().getSportPlanData();
        List<SportPlanModel.DataBean.ActionDataBean> actionData = sportPlanData.get(position).getActionData();
        mSportPlanDataAdapter.setNewData(actionData);
    }

    private void showProgressDialog(String title, String message) {

        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog.show(NewSportPlanActivity.this, title, message, false);
        } else if (mProgressDialog.isShowing()) {
            mProgressDialog.setTitle(title);
            mProgressDialog.setMessage(message);
        }
        mProgressDialog.show();
    }

    private void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }
}
